import { assign, cloneDeep, omit } from 'lodash-es';
import { compile } from 'path-to-regexp';
import * as store from './store';

const toPath = compile('diff-config/user/:userId');
const getUser = async () => await Manycore.User.getUserAsync();

interface IDiffConfigEditable {
  omitKeys: string[];
}
interface IDiffConfig extends IDiffConfigEditable {
  key: string;
}

export const defaultDiffConfig: IDiffConfig = {
  key: 'modelId',
  omitKeys: ['plankId', 'mergeId', 'holeId', 'grooveId', 'code'],
};

function getFullConfig(config?: Partial<IDiffConfigEditable>): IDiffConfig {
  return assign(cloneDeep(defaultDiffConfig), omit(config, 'key'));
}

export async function getDiffConfig() {
  const { userId } = await getUser();
  const path = toPath({ userId });
  const config = await store.getItem<IDiffConfigEditable>({ key: path });
  return getFullConfig(config);
}

export async function updateDiffConfig(config: IDiffConfigEditable) {
  const { userId } = await getUser();
  store.setItem({
    key: toPath({ userId }),
    value: config,
  });
}
